#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>

#define BUF_SIZE 64
#define NO -1

void my_close(int sockfd,int fd_w){

    if(sockfd > 0){
        close(sockfd);
    }
    
    if(fd_w > 0){
        close(fd_w);
    }

    return;
}


int my_send(int sockfd,const char* buf,int length){

    int temp=0;
    int ftemp=0;

    while(1){
        
        ftemp=send(sockfd,buf+temp,length - temp,0);//0 阻塞(发送的缓冲区满/网络阻塞);
        if(ftemp == -1){
            perror("my_send err");
            return -1;
        }
        temp+=ftemp;
        if(temp >= length){
            break;
        }
        
    }
    return 0;
}


int main(int argc,char const *argv[]){
    if(argc < 2){
        printf("usage err\n");
        return -1;
    }
    int sockfd = socket(AF_INET,SOCK_STREAM,0);//ipv4,tcp
    if(sockfd == -1){
        perror("sock err");
        return -1;
    }
    //服务器地址:IP 端口号
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    // server_addr.sin_port =htons(atoi(argv[2]));
    server_addr.sin_port =htons(8888);

    // server_addr.sin_addr.s_addr=inet_addr(argv[1]);
    server_addr.sin_addr.s_addr=inet_addr("127.0.0.1");

    printf("IP=%s\n",inet_ntoa(server_addr.sin_addr));
    socklen_t addrlen= sizeof(server_addr);
    

    //连接
    if(connect(sockfd,(struct sockaddr*)&server_addr,addrlen) < 0){
        perror("coonet err");
        my_close(sockfd,NO);
        return -1;
    }
    printf("connet  success\n");

    //收发数据
    int fd_r = open(argv[1],O_RDONLY | O_CREAT,0666);
    if(fd_r == -1){
        perror("open err");
        my_close(sockfd,NO);
        return -1;
    }
    char buf[BUF_SIZE]={0};
    int temp = 0;
    while(1){
        memset(buf,0,BUF_SIZE);
        temp =read(fd_r,buf,BUF_SIZE);
        if(temp == -1){
            perror("read err");
            my_close(sockfd,fd_r);
            return -1;
        }
        else if(temp == 0){
            printf("send complete\n");
            break;
        }
        
        if(my_send(sockfd,buf,temp) == -1){ //send 不一定会一次全部发送完，分多次发送完
            perror("send err");
            break;
        }
        
    }


    //关闭
    my_close(sockfd,fd_r);


    return 0;
}
